from app import create_app
from flask import render_template, jsonify
from flask import request
from app.model_train_predict.lstm_model_train import LSTMModelTrainPredict
from app.spectrum.neo4j_map import Neo4jMap
app = create_app()


@app.route('/')
def hello_world(): # put application's code here
    #last_model = LSTMModelTrainPredict()
    #last_model.model_application('train')
    return render_template('index.html')
@app.route('/lstm_crf_predict',methods = ['POST'])
def lstm_crf_predict():
    lstm_model_predict = LSTMModelTrainPredict()
    text = request.get_json()
    print(text)
    result = lstm_model_predict.model_application('predict',text['text'])
    first_key = list(result.keys())[0] if result else 'not'
    first_value = list(result.values())[0] if result else 'not'
    result = {
        'text':first_key,
        'type':first_value
    }
    return jsonify({'success':200,'result':result,'text':text['text']})
#neo4j操作
@app.route("/neo4j")
def neo4j():
    # 实例化对象
    neo_map = Neo4jMap()
    # 连接数据库
    neo_map.neo4j_connect()
    neo_map.load_file_create_map()
    nodes, edges, length = neo_map.get_visualization_data(100)
    return jsonify({
        'nodes': nodes,
        'edges': edges,
        'count': len(nodes)
    })

@app.route('/graph')
def neo4j_graph():
    return render_template('index4.html')
@app.route("/all")
def get_all_spo():
    # 实例化NeoGraph对象
    neo_map = Neo4jMap()
    # 建立连接
    neo_map.neo4j_connect()
    # 根据条件过滤SPO关系
    spo_list, count, timestamp = neo_map.get_all_spo()
    return jsonify({
        'count': count,
        'spo_list': spo_list,
        'timestamp': timestamp
    })

# 条件过滤
@app.route("/filter")
def get_filtered_spo():
    # 实例化NeoGraph对象
    neo_map = Neo4jMap()
    # 建立连接
    neo_map.neo4j_connect()
    # 根据条件过滤SPO关系
    start_label = request.args.get('start_label', '')
    rel_type = request.args.get('rel_type', '')
    end_label = request.args.get('end_label', '')
    search_term = request.args.get('search', '')
    count, spo_list, query, timestamp = neo_map.get_filtered_spo(start_label, rel_type, end_label, search_term)
    return jsonify({
        'count': count,
        'spo_list': spo_list,
        'query': query,
        'timestamp': timestamp
    })

# 获取数据库元数据
@app.route('/metadata')
def get_metadata():
    # 实例化NeoGraph对象
    neo_map = Neo4jMap()
    # 建立连接
    neo_map.neo4j_connect()
    # 获取元数据
    labels, relationship_types, node_count, relationship_count = neo_map.get_metadata()
    return jsonify({
        'labels': labels,
        'relationship_types': relationship_types,
        'node_count': node_count,
        'relationship_count': relationship_count
    })
if __name__ == '__main__':
    app.run(host='0.0.0.0',port=6868,debug=True)
